import * as moment from 'moment';
import { HistoryType } from './HistoryType';
import { LcDocument } from '../../types/editor.type';

/**
 * 根据上一次保存的时间与当前时间来决定 HistoryType
 *
 * @param {Date} lastSavedAt 上一次保存的时间(时间戳)
 * @return {HistoryType} 历史记录类型
 */
export function determineHistoryType(lastSavedAt: number) {
  const now = moment();
  const lastSavedMoment = moment(lastSavedAt);
  const duration = moment.duration(now.diff(lastSavedMoment));

  if (duration.asMinutes() <= 1) {
    return HistoryType.INSTANT;
  } else if (duration.asHours() <= 1) {
    return HistoryType.SHORT_TERM;
  } else if (duration.asHours() <= 24) {
    return HistoryType.MID_TERM;
  } else {
    return HistoryType.LONG_TERM;
  }
}

/**
 * 计算文档差异
 */
export function calculateDiff(
  oldDoc: LcDocument,
  newDoc: LcDocument,
): Record<string, any> {
  const diff: Record<string, any> = {};

  // 关键字段变化检测
  const keyFields: (keyof LcDocument)[] = [
    'schema',
    'title',
    'description',
    'fileName',
    'route',
    'componentsMap',
    'utilsMap',
    'pageConfig',
  ];

  for (const field of keyFields) {
    const oldValue = oldDoc[field];
    const newValue = newDoc[field];

    // 处理 schema 字段的特殊情况
    if (field === 'schema') {
      const oldSchema =
        typeof oldValue === 'string' ? oldValue : JSON.stringify(oldValue);
      const newSchema =
        typeof newValue === 'string' ? newValue : JSON.stringify(newValue);
      if (oldSchema !== newSchema) {
        diff.schema = newValue;
      }
      continue;
    }

    // 其他字段的比较
    if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
      diff[field] = newValue;
    }
  }

  return diff;
}
